<template>
    <el-container class="wrapper">

        <el-container class="mid-wrapper">

            <el-main class="main">
                <el-steps :active="active" finish-status="success">
                    <el-step title="Check" />
                    <el-step title="Confirm" />
                    <el-step title="Complete" />
                </el-steps>
                <div v-if="active == 0">
                    <div class="cart-div">
                        <el-table :data="store.state.shopCart" stripe style="width: 100%" :key="cartItem">
                            {{ carts }}
                            <el-table-column prop="itemId" label="itemid" />
                            <el-table-column prop="quantity" label="quantity">
                                <template #default="scope">
                                    <!-- <el-input-number :step="1" v-model="scope.row.quantity" @change="quantityChange(scope.row.quantity, scope.$index)" :min='1' :max="10" /> -->
                                    <el-row>
                                        <el-col span="8">
                                            <el-button type="info" plain
                                                @click="setQuantity(scope.row, scope.$index, -1)">-
                                            </el-button>
                                        </el-col>
                                        <el-col span="8">
                                            <el-input v-model="scope.row.quantity"
                                                @change="quantityChange(scope.row.quantity, scope.$index)" />
                                        </el-col>
                                        <el-col span="8">
                                            <el-button type="info" plain
                                                @click="setQuantity(scope.row, scope.$index, 1)">+
                                            </el-button>
                                        </el-col>
                                    </el-row>
                                </template>
                            </el-table-column>
                            <el-table-column prop="price" label="price" />
                            <el-table-column fixed="right" label="Operations">
                                <template #default="scope">
                                    <el-button type="text" size="small" @click.prevent="deleteRow(scope.$index)">Remove
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table><br>
                        <div class="sum">TotalPrice : {{ totalPrice }}</div>
                    </div><br>
                    <div class="submit">
                        <el-button @click="onSubmit">去结算</el-button>
                    </div>
                </div>

                <div v-if="active == 1">
                    <el-form :model="form" label-width="120px">
                        <el-form-item label="国家">
                            <el-select v-model="form.country" placeholder="please select your country">
                                <el-option label="China" value="China" />
                                <el-option label="USA" value="USA" />
                                <el-option label="England" value="UK" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="城市">
                            <el-input v-model="form.city" />
                        </el-form-item>
                        <el-form-item label="收货人姓名">
                            <el-input v-model="form.name" />
                        </el-form-item>
                        <el-form-item label="手机号码">
                            <el-input v-model="form.telephone" />
                        </el-form-item>
                        <el-form-item label="详细地址">
                            <el-input v-model="form.shipaddress" />
                        </el-form-item>
                        <el-form-item label="备用地址地址">
                            <el-input v-model="form.billaddress" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="pay">去支付</el-button>
                        </el-form-item>
                    </el-form>
                </div>

            </el-main>


        </el-container>

    </el-container>
</template>

<script setup>
import { ref } from "vue";
import axios from 'axios';
import router from '../router';
import { ElMessage, useRestoreActive } from "element-plus";
import { createDOMCompilerError } from "@vue/compiler-dom";
import { useStore } from "vuex";
import { computed } from "@vue/reactivity";

const sideWidth = ref('300px');

const active = ref(0)

const form = ref({})

const store = new useStore();
const username = store.state.userInfo.username;
var carts = store.state.shopCart;

console.log(store.state);

const totalPrice = computed(() => {
    return carts.reduce((total, curr) => {
        console.log(total);
        return total += curr.quantity * curr.price;
    }, 0)
})

const setQuantity = (row, index, change) => {
    const quantity = change + row.quantity;
    if (quantity != 0)
        store.commit("setQuantity", { index, quantity });
}

const pay = () => {
    axios.post("/order/addOrder", form.value).then(async res => {
        if(res.data.status == 0){
             ElMessage({
                    message: res.data.msg,
                    type:'success'
                    });

                await axios.post("/account/alipay?outTradeNo=username2&subject=ItemList&body='5月1日'&totalAmount=" + totalPrice.value).then(res => {
                console.log(res.data);
                console.log("【支付宝返回】" + res.data);
                //这里是跳转新的页面
                document.querySelector('body').innerHTML = res;
                const div = document.createElement('div');
                div.innerHTML = res.data;
                document.body.appendChild(div);

                // _blank -- 在新窗口中打开链接
                // _parent -- 在父窗体中打开链接
                // _self -- 在当前窗体打开链接,此为默认值
                // _top -- 在当前窗体打开链接，并替换当前的整个窗体(框架页)
                document.forms[0].setAttribute('target', '_blank');// 新建窗口页面
                document.forms[0].submit();


            }).catch(function (error) {
                console.log(error)
            });
        }else{
            ElMessage({
                message: res.data.msg,
                    type:'warning'
            });
        }
    })
}

const quantityChange = function (a, index) {
    axios({
        method: 'POST',
        url: "account/" + username + "/cart/" + carts[index].itemId,
        params: {
            quantity: a,
        },
    }).then(Response => {
        store.commit("setCart", Response.data.data);
        for (var i = 0; i < Response.data.data.length; i++) {
            totalPrice += Response.data.data[i].price;
        }
        // store.commit("setTotalPrice", totalPrice);
    })
};

const widthChange = function () {
    sideWidth.value = sideWidth.value === '300px' ? '100px' : '300px';
};

const deleteRow = function (index) {
    axios({
        method: 'POST',
        url: "/account/" + username + "/cart/" + carts[index].itemId,
        params: {
            quantity: 0,
        },
    }).then(Response => {
        store.commit("setCart", Response.data.data);
        for (var i = 0; i < Response.data.data.length; i++) {
            totalPrice += Response.data.data[i].price;
        }
        // store.commit("setTotalPrice", totalPrice);
    })

};

console.log(carts)
console.log(totalPrice);



const onSubmit = () => {
    active.value++;
    // router.push({ path: "/addOrder" });

};

</script>

<style lang="postcss" scoped>
.wrapper {
    @apply h-full w-full
}

.header {
    @apply bg-indigo-200 flex items-center justify-between
}

._menu,
.__menu {
    cursor: pointer;
    width: 40px;
    height: 40px;
}

#icon1,
#icon2 {
    width: 40px;
    height: 40px;
}


.footer {
    @apply bg-indigo-200
}

.mid-wrapper {
    @apply h-full
}

.right-aside {
    @apply h-full bg-gray-100
}

.left-aside {
    @apply h-full bg-gray-100
}

._admin {
    @apply flex ml-[900px]
}

.main {
    @apply h-full w-full
}

.sum {
    @apply ml-[650px]
}
</style>